<?php
/**
 * Created by PhpStorm.
 * User: duanshuai
 * Date: 2018/6/22
 * Time: 下午3:52
 */

namespace app\index\model;

use think\Model;
class MonthBill extends Model
{
    //跟新month表数据,累计每月花费
    public function updateMonthBill($count,$cost){
        //如果有本月花费数据就更新,没有就新增加一条
        $month_start = strtotime(date('Y-m'));//指定月份月初时间戳
        $month_end = mktime(23, 59, 59, date('m', strtotime(date('Y-m')))+1, 00);;//指定月份月末时间戳

        //更新数据,更新失败,就增加一条

        $list = self::where('count',$count)->whereTime('create_time','between',[$month_start,$month_end])->setInc('cost_all',$cost);

        if (!$list) {
            //数据不存在,增加数据
            self::save(['count'=>$count,'cost_all'=>$cost,'month'=>date('Y-m')]);

        }

    }



    /*
     * 查询month表数据 分页
     * */
    public function findMonthBill($count,$page){
        $data = [];

        $list = self::where('count',$count)-> order('month','desc') -> limit(10*($page-1),10*$page) ->field('month,cost_all')-> select();

        $data['total'] = self::where('count',$count)->count();

        if ($list) {
            $list = collection($list)->toArray();
        }
        $data['data'] = $list;


        return $data;
    }

    /*
     * 查询month表数据 分页
     * */
    public function findYearBill($count,$year){
        $data = [];

        $list = self::where('count',$count) ->whereLike('month',$year.'%')-> order('month','des') ->field('month,cost_all')-> select();

//        $data['total'] = self::where('count',$count)->count();

        if ($list) {
            $list = collection($list)->toArray();
        }
        $data['data'] = $list;


        return $data;
    }


    /*
     * 同步账单表数据到 nonth
     * */
    public function updateMonth_tongbu($count){
        $bill = new DailyBill();
        $data = $bill ->findCountBill_month_cost($count);


        foreach ($data as $k => $v) {
            $list = self::where(['count'=>$count,'month'=>$k])->find();

            if (empty($list)){//没有数据,更新失败,创建数据
                $mod = new MonthBill(['count'=>$count,'cost_all'=>$v,'month'=>$k]);

                $mod->save();

            }else{

                $result = self::where(['count'=>$count,'month'=>$k]) ->update(['cost_all'=>$v]);
            }

        }
    }

}